package com.controller;

import com.entity.Response;
import com.entity.pojo.WrUser;
import com.service.UserService;
import com.utils.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @RequiresRoles("admin")
    @GetMapping("/listUser")
    public Response listUser() {
        return new Response().setSuccess().appendMsg("list", userService.listUser());
    }

    @RequiresRoles("admin")
    @PostMapping("/insert")
    public Response insertUser(@RequestBody WrUser user) {
        int res = userService.insertUser(user);
        return res > 0 ? new Response().setSuccess() : new Response().setFailed();
    }

    @RequiresRoles("admin")
    @DeleteMapping("/delete")
    public Response deleteUser(@RequestParam("id") Integer id) {
        int result = userService.deleteUser(id);
        if (result > 0) {
            return new Response().setSuccess();
        } else {
            return new Response().setFailed();
        }
    }

    @GetMapping("/getInfo")
    @RequiresRoles(value = {"admin", "user"}, logical = Logical.OR)
    public Response getInfo() {
        String token = (String) SecurityUtils.getSubject().getPrincipal();
        String username = JwtUtil.getUuid(token);
        String role = userService.getRole(new WrUser().setUsername(username));
        return new Response().setSuccess().appendMsg("username", username).appendMsg("roleName", role);
    }

    @PutMapping("/resetUserPassword")
    @RequiresRoles(value = {"admin"})
    public Response resetUserPassword(@RequestBody WrUser user) {
        int res = userService.resetUserPassword(user.getId());
        return res > 0 ? new Response().setSuccess() : new Response().setFailed();
    }

    @PutMapping("")
    @RequiresRoles(value = {"admin"})
    public Response UpdateUser(@RequestBody WrUser user) {
        int res = userService.updateUser(user.setUpdateTime(LocalDateTime.now()));
        return res > 0 ? new Response().setSuccess() : new Response().setFailed();
    }
}
